<?php
// +----------------------------------------------------------------------
// | MubinAdmin
// +----------------------------------------------------------------------
// | 版权所有 2015~2020 泉州市牧滨电子商务有限公司 [ http://www.mubin.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://www.mubin.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/mubin/MubinAdmin
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\service\AdminUserService;
use app\common\traits\{Entrust, Jump};
use app\common\facade\UserInfo;
use think\Exception;
use think\facade\View;

class Login
{
	use Entrust,Jump;

    /**
     * 设置视图并输出
     * @param array  $value 赋值
     * @param string $template 模板名称
     * @return mixed
     * @throws \Exception
     */
    protected function setView(?array $value = [], ?string $template = '')
    {
        //检测模板初始化
        View::config($this->app->config->get('app.template',[]));
        return View::fetch($template ?: '',$value ?: []);
    }
    
    /**
     * 首页
     * @return mixed
     * @throws \Exception
     */
    public function index()
    {
        if (UserInfo::online() === true) {
            return $this->redirect('index/index');
        }
        $loginskey = session('loginskey');
        if (empty($loginskey)) {
            $loginskey = uniqid();
            session('loginskey', $loginskey);
        }
        $remember = $this->app->cookie->get('remember');
        return $this->setView(['remember' => $remember,'loginskey' => $loginskey],'index');
    }

    /**
     * 登录
     * @param AdminUserService $adminUserService
     * @return mixed
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function login(AdminUserService $adminUserService)
    {
        //判断是否ajax登录
        if ($this->app->request->isAjax() === false) {
            return $this->error('非法请求','index/index');
        }
        //腾讯验证码
        //$this->app->config->get('tencent.captcha.status') && $this->tencentCaptcha();
        $userId = $adminUserService->login($this->app->request->param());
        return $this->success('登录成功,页面马上跳转~', 'index/index');
    }

    /**
     * 退出
     * @return mixed
     */
    public function logout()
    {
        if (UserInfo::online() === false) {
            return $this->redirect('Login/index',302);
        }
        UserInfo::logout();
        return $this->redirect('Login/index', 302);
    }
}